//
//  ShouJiChongZhiViewController.m
//  1243
//
//  Created by 袖手旁觀 on 16/3/25.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "ShouJiChongZhiViewController.h"
#import "CreditButtonView.h"

#import "AFNetworking.h"
#import "FkfsView.h"

//弹出密码输入框
#import "RKAlertView.h"
#import "ReadLoginData.h"

@interface ShouJiChongZhiViewController ()<UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, FkfsViewDelegate>
{
    UIView *lineView;
    CGFloat creditBtnheigh;
    NSString *tempStr;
    UIView *tempView;
    
    //判断选择的是充值话费还是充值流量
    BOOL judgeBool;
    
    //数组, 用于存放充值金额等信息的数组
    NSArray *moneyCount;
    NSArray *otherArray;
    NSArray *flowArray;
    NSArray *flowMonetArray;
    
    //用户名,,可以在登陆后存储到本地,然后在从本地读取数据
    NSString *usernametext;
    //付款方式
    NSString *fkfsStr;
    //二级付款密码
    NSString *passwordTwo;
    
    
    
    
}
@property (nonatomic, strong)UITextField *PhoneNumTextField;
@property (nonatomic, strong)UILabel *NumberInfo;
@property (nonatomic, strong)UIButton *payBtn;
@property (nonatomic, strong)UITableView *CreditTableview;

@property (nonatomic, strong)FkfsView *tempfkfs;

@property (nonatomic, strong)UIView *firstView;
@property (nonatomic, strong)UIView *secondView;

@property (nonatomic, strong)UIButton *leftBtn;

@property (nonatomic, strong)UILabel *titleLabel;

@end

@implementation ShouJiChongZhiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self addBaseUI];
    
    //初始化
    [self initSomething];
    
    [self addMoreCreditUI];
}

- (void)addBaseUI {
    self.firstView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WEITH, HIGHT*0.1)];
//    self.firstView.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
    
    [self.view addSubview:self.firstView];
    
    self.secondView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, WEITH, CGRectGetHeight(self.firstView.frame)-20)];
//    self.secondView.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
    [self.firstView addSubview:self.secondView];
    
    
    self.leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.leftBtn.frame = CGRectMake(5, 10, CGRectGetHeight(self.secondView.frame), CGRectGetHeight(self.secondView.frame)-20);
    [self.secondView addSubview:self.leftBtn];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(WEITH/2 - 80, 10, 160, self.secondView.frame.size.height - 20)];
    self.titleLabel.font = [UIFont systemFontOfSize:18];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.secondView addSubview:self.titleLabel];
    
}

-(void)initSomething {
    tempStr = @"30.00";
    //    judgeBool = YES;
    moneyCount = @[@"30元", @"50元", @"100元"];
    otherArray = @[@"30.00", @"50.00", @"100.00"];
    
}

- (void)addMoreCreditUI {
//    [self addCreditTopUI];
    //    [self addSelectbtnUI];
    
    [self addPhoneTextUI:self.view];
    [self addCreditBtns:self.view];
    //    [self addPayButton];
    [self addCreditTableview];
    
}

- (void)addCreditTableview {
    self.CreditTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(tempView.frame)+5, WEITH, HIGHT-CGRectGetMaxY(tempView.frame)-5) style:UITableViewStyleGrouped];
    self.CreditTableview.delegate = self;
    self.CreditTableview.dataSource = self;
    self.CreditTableview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.CreditTableview];
    self.CreditTableview.scrollEnabled = NO;
    
}
//首次进入得时候添加话费充值金额的视图
- (void)addCreditBtns:(UIView *)fatherview {
    UIView *smallLine = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tempfkfs.frame)+29, WEITH, 1)];
    smallLine.layer.borderWidth = 1;
    smallLine.layer.borderColor = [UIColor colorWithRed:217/255. green:217/255. blue:217/255. alpha:1].CGColor;
    [fatherview addSubview:smallLine];
    
    
    
    CGFloat weith = (WEITH-30)/3;
    CGFloat heigh = (weith/3)*2;
    NSInteger k = 0;
    tempView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tempfkfs.frame)+30, WEITH, 40+heigh*3)];
    tempView.userInteractionEnabled = YES;
    [fatherview addSubview:tempView];
    
    
    for (NSInteger i=0; i < 3; i++) {
        
        CreditButtonView *creditBtnview = [[CreditButtonView alloc] initWithFrame:CGRectMake(10+(weith+5)*i, 10, weith,heigh)];
        UIButton *creditBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        creditBtn.frame = CGRectMake(0, 0, weith,heigh);
        creditBtnview.MoneyLabel.text = [NSString stringWithFormat:@"%@", moneyCount[k]];
        creditBtnview.CountMoneyLabel.text = [NSString stringWithFormat:@"售价:%@元", otherArray[k]];
        creditBtnview.tag = 700+k;
        [tempView addSubview:creditBtnview];
        [creditBtnview addSubview:creditBtn];
        [creditBtn addTarget:self action:@selector(CreditButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        if (i==0) {
            creditBtnview.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
            creditBtnview.MoneyLabel.textColor = [UIColor whiteColor];
            creditBtnview.CountMoneyLabel.textColor = [UIColor whiteColor];
        }
        k++;
        
    }
    
}


//充值话费的点击事件
- (void)CreditButtonClick:(UIButton *)button {
    for (CreditButtonView *btnview in tempView.subviews) {
        if (btnview.tag == button.superview.tag) {
            btnview.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
            btnview.MoneyLabel.textColor = [UIColor whiteColor];
            btnview.CountMoneyLabel.textColor = [UIColor whiteColor];
        } else {
            btnview.backgroundColor = [UIColor whiteColor];
            btnview.MoneyLabel.textColor = [UIColor blackColor];
            btnview.CountMoneyLabel.textColor = [UIColor blackColor];
        }
    }
    
    
    tempStr = otherArray[button.superview.tag - 700];
    
    [self.CreditTableview reloadData];
    
}

- (void)addPhoneTextUI:(UIView *)fatherview {
    
    //手机号码
    UITextField *phoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(self.secondView.frame)+10, WEITH-20, 40)];
    phoneTextField.placeholder = @"请输入手机号码";
    phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    //UITextFieldViewModeAlways
    phoneTextField.delegate = self;
    phoneTextField.clearButtonMode = UITextFieldViewModeAlways;
    phoneTextField.font = [UIFont systemFontOfSize:20];
    [phoneTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.PhoneNumTextField = phoneTextField;
    [fatherview addSubview:self.PhoneNumTextField];
    
    //手机号码归属地
    self.NumberInfo = [[UILabel alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(self.PhoneNumTextField.frame) + 5, WEITH - 20, 20)];
    self.NumberInfo.text = @"手机号码归属地";
    self.NumberInfo.font = [UIFont systemFontOfSize:12];
    [fatherview addSubview:self.NumberInfo];
    
    self.tempfkfs = [[FkfsView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(self.NumberInfo.frame)+5, WEITH-20, 60)];
    self.tempfkfs.titlelabel.text = @"支付方式";
    self.tempfkfs.layer.borderWidth = 1;
    self.tempfkfs.layer.cornerRadius = 6;
    self.tempfkfs.layer.masksToBounds = YES;
    //    fkfsView.backgroundColor = [UIColor yellowColor];
    self.tempfkfs.delegate = self;
    
    [fatherview addSubview:self.tempfkfs];
    
    
    
}
-(void)fkfsViewBtnClick:(UIButton *)button {
    if (button.tag == 890) {
        fkfsStr = @"0";
    } else {
        fkfsStr = @"1";
    }
    [self.CreditTableview reloadData];
}
//- (void)addCreditTopUI {
//    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
//    image1.image = [UIImage imageNamed:@"goback-icon.png"];
//    [self.secondView addSubview:image1];
//    self.leftBtn.hidden = YES;
//    
//    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
//    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
//    [self.secondView addSubview:goBackBtn];
//    
//    self.titleLabel.text = @"话费充值";
//}

//- (void)gobackClick {
//    [self dismissViewControllerAnimated:YES completion:nil];
//}
//52.   147  225

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return nil;
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return HIGHT*0.9;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, HIGHT*0.1, WEITH, HIGHT*0.9)];
    headerView.userInteractionEnabled = YES;
    
    self.payBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.payBtn.frame = CGRectMake(30, 20, WEITH-60, 30);
    self.payBtn.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
    [self.payBtn setTitle:[NSString stringWithFormat:@"立即支付:%@元", tempStr] forState:UIControlStateNormal];
    [self.payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.payBtn addTarget:self action:@selector(payBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:self.payBtn];
    headerView.backgroundColor = [UIColor whiteColor];
    return headerView;
    
}


#pragma mark -- 支付按钮
- (void)payBtnClick{
    NSDictionary *dic = [ReadLoginData readLoginData];
    if (dic.allKeys.count == 0) {
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您尚未登录,请登录后再次操作" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
    }else {
        if (self.PhoneNumTextField.text.length == 0) {
            UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入手机号码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alview show];
        }else if (self.PhoneNumTextField.text.length<11) {
            UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您的号码输入有误,请输入11位的手机号码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alview show];
        }else {
            //点击后应该弹出二级密码输入框,,确定后在进行数据解析
            //弹出密码输入框
            [RKAlertView showAlertPlainTextWithTitle:@"提示框" message:nil cancelTitle:@"取消" confirmTitle:@"确认" alertViewStyle:UIAlertViewStylePlainTextInput confrimBlock:^(UIAlertView *alertView) {
                NSLog(@"确认了输入：%@",[alertView textFieldAtIndex:0].text);
                passwordTwo = [alertView textFieldAtIndex:0].text;
                [self phoneCardDatasources];
                
            } cancelBlock:^{
                //                    NSLog(@"取消了");
            }];
        }
    }
    
    
    
    
    
}



#pragma mark -- UITextFieldDelegate
//触摸空白处回收键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.PhoneNumTextField resignFirstResponder];
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.PhoneNumTextField) {
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength >= 12) {
            return NO;
        }
    }
    
    
    return YES;
}

//实时监控键盘的状态
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.PhoneNumTextField) {
        if (textField.text.length >=12) {
            textField.text = [textField.text substringToIndex:12];
        }
        if (textField.text.length >10) {
            [self receiveMessage:self.PhoneNumTextField.text];
        }
        
        
    }
    
#pragma mark -- 在这里判断手机号码的归属地
    
}


//用于对手机号码的归属地进查询
- (void)receiveMessage:(NSString *)phoneStr {
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
//    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *account = phoneStr;
    
    
    NSDictionary *param = @{@"account":[NSString stringWithFormat:@"%@", account]};
    
    
    __weak ShouJiChongZhiViewController *moreself = self;
    
    [mgr GET:@"http://www.ylgw8.com/Index/getGS/" parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [moreself toArrayOrNSDictionary:responseObject];
        
        
        self.NumberInfo.text = [NSString stringWithFormat:@"%@",  [NSString stringWithFormat:@"%@", dic[@"message"]]];
        [self.CreditTableview reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}



- (void)phoneCardDatasources {
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
//    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //用户名
    NSString *username = usernametext;
    //平台类型(1是PC,2是其他平台)
    NSString *type = @"2";
    //充值手机号码
    NSString *account = self.PhoneNumTextField.text;
    //充值金额
    NSString *jine = @"100000";
    //运营商
    NSString *yys = self.NumberInfo.text;
    //二级付款密码
    NSString *pwdtwo = passwordTwo;
    //付款方式(0是积分付款,,1是余额付款)
    NSString *fkfs = fkfsStr;
    
    
    
    
    NSDictionary *param = @{@"username":[NSString stringWithFormat:@"%@", username], @"type":[NSString stringWithFormat:@"%@", type], @"account":[NSString stringWithFormat:@"%@", account], @"jine":[NSString stringWithFormat:@"%@", jine], @"yys":[NSString stringWithFormat:@"%@", yys], @"pwdtwo":[NSString stringWithFormat:@"%@", pwdtwo], @"fkfs":[NSString stringWithFormat:@"%@", fkfs]};
    
    [mgr POST:@"http://www.ylgw8.com/Gwc/hfcz" parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [self toArrayOrNSDictionary:responseObject];
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@", dic[@"message"]] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
        
        NSLog(@"jjjjj");
        [self.CreditTableview reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    

}



// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}

@end
